/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package bluetooth;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import ota.Myhex;

@SuppressLint("NewApi")
public class BluetoothLeService extends Service {
    private final static String TAG = "蓝牙服务";

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
//    private String mBluetoothDeviceAddress;
    public static BluetoothGatt mBluetoothGatt;
    private int mConnectionState = STATE_DISCONNECTED;
    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;
    private String MTU_VALUS;
    //蓝牙开启的服务
    List<BluetoothGattService>    listBluetoothGattService;

    /**********************************************************************************************/
    //蓝牙连接成功
    public final static String ACTION_GATT_CONNECTED = "com.touchgfx.health.le.ACTION_GATT_CONNECTED";
    //蓝牙断开连接
    public final static String ACTION_GATT_DISCONNECTED = "com.touchgfx.health.le.ACTION_GATT_DISCONNECTED";
    //蓝牙服务发现到
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.touchgfx.health.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "com.touchgfx.health.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA = "com.touchgfx.health.le.EXTRA_DATA";
    public final static String EXTRA_DATA_MTU = "com.touchgfx.health.le.EXTRA_DATA_MTU";
    public final static String ACTION_NOTIFICATION = "com.touchgfx.health.le.NOTIFICATION";//通知消息
    public final static String ACTION_CALL = "com.touchgfx.health.le.CALL";//电话通知消息


    /**********************************************************************************************/






    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                gatt.discoverServices();//蓝牙连接成功之后开始发现蓝牙开放的服务
                // 设置mtu值
                setMTU(500);

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }

        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {
                listBluetoothGattService=gatt.getServices();
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.i("读取出来的值", gatt + " " + characteristic + " " + status);

            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.w(TAG, "读取数据成功onServicesDiscovered received: " + status);
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            } else {
                Log.w(TAG, "读取数据onServicesDiscovered received: " + status);

            }
        }
        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            Log.w(TAG, "当前mtu值: " + mtu);
            MTU_VALUS = mtu + "";
            broadcastUpdate(EXTRA_DATA_MTU, null);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            Log.w(TAG, "写数据onServicesDiscovered received: ");

        }
    };

    /**
     * 蓝牙连接上发送广播
     * @param action
     */
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    /**
     * 将数据广播给前台页面
     * @param action
     * @param characteristic
     */
    private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {

        if (characteristic == null) {
            Intent intent2 = new Intent(EXTRA_DATA_MTU);
            intent2.putExtra(EXTRA_DATA_MTU, MTU_VALUS);
            sendBroadcast(intent2);

        } else {
            final Intent intent = new Intent(action);
            final byte[] data = characteristic.getValue();
            if (data != null && data.length > 0) {
                intent.putExtra(EXTRA_DATA, Myhex.buffer2String(data) );

            } else {
                intent.putExtra(EXTRA_DATA, "空数据");
            }
            sendBroadcast(intent);
        }

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public boolean setMTU(int mtu) {
        Log.d("BLE", "setMTU " + mtu);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mtu > 20) {
                boolean ret = mBluetoothGatt.requestMtu(mtu);
                Log.d("BLE", "requestMTU " + mtu + " ret=" + ret);
                return ret;
            }
        }
        return false;
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    public boolean initialize() {
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }
        return true;
    }

    public boolean connect(final String address) {

        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }

        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        return true;

    }

    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }


    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    private void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * 向蓝牙模块写数据
     */
    public boolean setCharacteristicNotificationToBliutooth(BluetoothGattCharacteristic characteristic, boolean enabled, byte[] data) {
        boolean isSendSusccess = false;
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        @SuppressWarnings("unused")
        boolean rr = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        characteristic.setValue(data);
        characteristic.setWriteType(2);
        boolean writeCharacteristic = mBluetoothGatt.writeCharacteristic(characteristic);
        isSendSusccess = writeCharacteristic;
        Log.e("tag_send", "\u53d1\u9001  " + writeCharacteristic + " " + Myhex.buffer2String(data));
        return isSendSusccess;
    }

    /**
     * 设置蓝牙模块可以回复数据
     */
    public boolean setCharacteristicNotificationToBliutooth2(BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        if (isEnableNotification) {
            List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
            if (descriptorList != null && descriptorList.size() > 0) {
                for (BluetoothGattDescriptor descriptor : descriptorList) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(descriptor);
                }
            }
        }
        return true;

    }

    /**
     * 获取蓝牙服务
     */
    public List<BluetoothGattService> getSupportedGattServiceList(){
        return listBluetoothGattService;
    }
    /**
     * 通过指定的uuid获取蓝牙服务
     */
    public List<BluetoothGattService> getSupportedGattService(UUID uuid) {
        if (mBluetoothGatt == null)
            return null;
        List<BluetoothGattService> list = new ArrayList<BluetoothGattService>();
        BluetoothGattService mBluetoothGattService = mBluetoothGatt.getService(uuid);
        if (mBluetoothGattService == null) {
            list = null;
        } else {
            list.add(mBluetoothGattService);
        }
        return list;

    }

    /**
     * 通过指定的uuid获取蓝牙服务
     */
    public BluetoothGattCharacteristic getSupportedGattCharacteristic( BluetoothGattService mBluetoothGattService,UUID uuid) {
       return  mBluetoothGattService.getCharacteristic(uuid);
    }
}
